import { 
  unitWidth, barHeight, barMargin, taskNamePaddingLeft, 
  getRealDuration, includeHoliday, getLeftHandleBar, getRightHandleBar,
  createLeftArrowRect, createRightArrowRect, getTaskBarMoveLine,
  syncLocal, setCurrentGroup, Popup, ContextMenu
} from './initialization.js';

/**
 * 绘制任务条
 * @param {Object} zr ZRender实例
 * @param {Array} tasks 任务数组
 * @param {Object} chartState 图表状态对象
 * @param {Function} redrawChart 重绘图表函数
 * @param {Object} currentGroup 当前操作组
 * @returns {number} 绘制的任务条数量
 */
export function drawTaskBars(zr, tasks, chartState, redrawChart, currentGroup) {
  let drawTaskBar = 0;
  const boundingLeft = Math.floor(chartState.lastScrollX / unitWidth);
  const boundingRight = Math.floor((chartState.lastScrollX + chartState.canvasWidth) / unitWidth);

  tasks.forEach(function (task, index) {
    if (!task?.name) return;
    
    // 性能优化：在视口外跳过
    if (index > Math.floor((chartState.canvasHeight - chartState.chartStartY) / (barHeight + barMargin))) return;
    
    const showLeftArrow = task.start <= boundingLeft;
    const showRightArrow = (task.start + task.duration) > boundingRight;

    // 计算位置和尺寸
    const x = chartState.chartStartX + task.start * unitWidth;
    const y = chartState.chartStartY + (barHeight + barMargin) * index;
    const width = task.duration * unitWidth;
    const taskBarRect = {
      width,
      height: barHeight
    };

    // 创建左右箭头
    const leftArrow = createLeftArrowRect(x, y, task, taskBarRect, showLeftArrow, boundingLeft, function() {
      // 这里需要更新全局的滚动状态，而不是局部的chartState
      // 由于redrawChart函数会重新计算chartState，我们只需要调用redrawChart
      redrawChart(true, (task.start - 3) * unitWidth, 0);
    });
    
    const rightArrow = createRightArrowRect(x, y, task, unitWidth, chartState.lastScrollX, chartState.canvasWidth, taskBarRect, showRightArrow, boundingRight, function() {
      // 这里需要更新全局的滚动状态，而不是局部的chartState
      // 由于redrawChart函数会重新计算chartState，我们只需要调用redrawChart
      redrawChart(true, (task.start + task.duration + 3) * unitWidth - chartState.canvasWidth, 0);
    });
    
    leftArrow && zr.add(leftArrow);
    rightArrow && zr.add(rightArrow);
    
    if (task.start > boundingRight || (task.start + task.duration) < boundingLeft) return;
    drawTaskBar++;

      // 创建任务组
  const group = createTaskGroup(x, y, width, task, index, chartState, tasks, redrawChart, currentGroup, zr);
    zr.add(group);
  });

  return drawTaskBar;
}

/**
 * 创建任务组
 * @param {number} x X坐标
 * @param {number} y Y坐标
 * @param {number} width 宽度
 * @param {Object} task 任务对象
 * @param {number} index 任务索引
 * @param {Object} chartState 图表状态对象
 * @param {Array} tasks 任务数组
 * @param {Function} redrawChart 重绘图表函数
 * @param {Object} currentGroup 当前操作组
 * @param {Object} zr ZRender实例
 * @returns {Object} 任务组
 */
function createTaskGroup(x, y, width, task, index, chartState, tasks, redrawChart, currentGroup, zr) {
  const group = new zrender.Group({
    x,
    y,
    draggable: true
  });

  // 创建任务矩形
  const rect = new zrender.Rect({
    shape: {
      x: 0,
      y: 0,
      width: width,
      height: barHeight,
      r: 6
    },
    style: {
      fill: task.fillColor
    },
    cursor: 'move'
  });
  group.add(rect);
  group.index = index;

  // 创建调整大小的手柄
  const w = 6;
  const box = rect.getBoundingRect();
  const leftBar = getLeftHandleBar(w, box, { width, height: barHeight }, redrawChart);
  leftBar.taskBar = rect;
  group.add(leftBar);

  const rightBar = getRightHandleBar(w, box, { width, height: barHeight }, redrawChart);
  rightBar.taskBar = rect;
  group.add(rightBar);

  // 添加文字元素
  addTaskTexts(group, task, width);

  // 设置事件处理
  setupTaskEvents(group, rect, task, index, chartState, tasks, redrawChart, currentGroup, zr);

  return group;
}

/**
 * 添加任务文字
 * @param {Object} group 任务组
 * @param {Object} task 任务对象
 * @param {number} width 宽度
 */
function addTaskTexts(group, task, width) {
  // 任务名称
  const taskName = new zrender.Text({
    style: {
      text: task.name,
      x: taskNamePaddingLeft,
      y: barHeight / 2 - 12 / 2,
      textFill: "white",
      textAlign: "left",
      textVerticalAlign: "middle",
      fill: "white"
    },
    cursor: 'move'
  });

  // 任务持续时间
  const taskDurationText = new zrender.Text({
    style: {
      text: `${getRealDuration(task, includeHoliday)}天`,
      x: width - taskNamePaddingLeft,
      y: barHeight / 2 - 12 / 2,
      textFill: "white",
      textAlign: "left",
      textVerticalAlign: "middle",
      fill: "white"
    },
    cursor: 'move'
  });
  
  const { width: taskDurationTextWidth } = taskDurationText.getBoundingRect();
  taskDurationText.attr({
    style: {
      x: width - taskDurationTextWidth - taskNamePaddingLeft
    }
  });

  // 资源分配文字
  const resourceText = new zrender.Text({
    style: {
      text: "Assigned to: " + task.resource,
      x: 0 + width + 5,
      y: barHeight / 2 + 0 - 12 / 2,
      textFill: "black"
    },
    cursor: 'normal'
  });

  // 如果放不下，显示到resourceText上去，隐藏taskName
  if (taskName.getBoundingRect().width + taskDurationTextWidth + taskNamePaddingLeft * 2 > width) {
    resourceText.attr({
      style: {
        text: task.name
      }
    });
    taskName.hide();
  }

  group.add(taskName);
  group.add(taskDurationText);
  group.add(resourceText);
}

/**
 * 设置任务事件
 * @param {Object} group 任务组
 * @param {Object} rect 任务矩形
 * @param {Object} task 任务对象
 * @param {number} index 任务索引
 * @param {Object} chartState 图表状态对象
 * @param {Array} tasks 任务数组
 * @param {Function} redrawChart 重绘图表函数
 * @param {Object} currentGroup 当前操作组
 * @param {Object} zr ZRender实例
 */
function setupTaskEvents(group, rect, task, index, chartState, tasks, redrawChart, currentGroup, zr) {
  // 鼠标悬停事件
  group.on("mouseover", function () {
    if (this.dragging) return;
    rect.attr("style", { fill: zrender.color.lift(task.fillColor, 0.3) });
  });

  group.on("mouseout", function () {
    if (this.dragging || this.resizing) return;
    rect.attr("style", { fill: task.fillColor });
  });

  // 拖拽逻辑
  let dragStartX = 0;
  let lastPosY = null;
  let lastBottomLine = null;

  group.on("dragstart", function (e) {
    if (this.resizing) return;
    dragStartX = e.event.zrX;
    setCurrentGroup(this);
  });

  group.on("drag", function (e) {
    if (this.resizing) return;
    const y = e.event.zrY - chartState.chartStartY;
    const posY = Math.floor(y / (barHeight + barMargin));
    
    if (lastPosY !== posY) {
      lastPosY = posY;
      zr.remove(lastBottomLine);
      const bottomLine = getTaskBarMoveLine(chartState.chartStartX, chartState.chartStartY, chartState.lastScrollX, chartState.timeScaleWidth, posY);
      lastBottomLine = bottomLine;
      bottomLine && zr.add(bottomLine);
      zr.refresh();
    }
  });

  group.on("dragend", function (e) {
    if (this.isContextMenu) {
      this.isContextMenu = false;
      return;
    }
    
    this.isDragging = false;
    
    if (this.resizing) {
      this.resizing = false;
      return;
    }

    const deltaX = e.event.zrX - dragStartX;
    const dir = deltaX < 0 ? -1 : 1;
    const delta = Math.abs(deltaX);
    const mod = delta % unitWidth;
    const offsetX = dir * (Math.floor(delta / unitWidth) + Math.floor(mod / (unitWidth / 2)));
    
    const y = e.event.zrY - chartState.chartStartY;
    const posY = Math.floor(y / (barHeight + barMargin));
    const offsetY = posY - index;
    
    task.start += offsetX;
    
    if (lastBottomLine && posY !== index) {
      // 删除当前项目
      tasks.splice(index, 1);
      // 移动当前项目到目标位置
      tasks.splice(posY > index ? posY - 1 : posY, 0, {...task});
    }
    
    if (offsetX || offsetY) {
      syncLocal();
    }
    
    setCurrentGroup(null);
    redrawChart(true);
  });

  // 设置子元素层级
  group.eachChild(function (child) {
    child.attr({
      z: 10
    });
  });

  // 双击事件
  group.on("dblclick", function () {
    Popup.show({
      currentIndex: this.index
    });
  });

  // 右键菜单事件
  group.on("contextmenu", function (e) {
    this.isContextMenu = true;
    e.event.preventDefault();
    const { zrX: x, zrY: y } = e.event;
    ContextMenu.show({
      currentIndex: this.index,
      position: {
        x,
        y
      }
    });
  });
} 